package com.engine.hikvision.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hikvision.artemis.sdk.ArtemisHttpUtil;
import com.hikvision.artemis.sdk.config.ArtemisConfig;
import dm.jdbc.util.StringUtil;
import sun.misc.BASE64Encoder;
import weaver.general.BaseBean;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

public class HikVisionApiUtil{

    private static int BUFFER = 1024;

    // 代理API网关nginx服务器ip端口
    private static final String HOST = "192.168.5.250:10443";

    // 秘钥appkey
    private static final String APP_KEY = "20685357";

    // 秘钥appSecret
    private static final String APP_SECRET = "gD4qCz1iprH4jiNLXu7A";

    private static final String ARTEMIS_PATH = "/artemis";

    public static DateTimeFormatter yyyyMMdd = DateTimeFormatter.ofPattern("yyyy-MM-dd");

    public static DateTimeFormatter yyyyMMddHHmmss = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    public static DateTimeFormatter yyyyMMddHHmm = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");

    /**
     * 调用POST请求类型接口
     */
    public static String callPostApi(String url, String body) throws Exception {
        new BaseBean().writeLog("begin do do post string artemis...");
        ArtemisConfig config = new ArtemisConfig();
        config.setHost(HOST);
        config.setAppKey(APP_KEY);
        config.setAppSecret(APP_SECRET);
        final String getCamsApi = ARTEMIS_PATH + url;
        Map<String, String> path = new HashMap<String, String>(2) {
            {
                put("https://", getCamsApi);
            }
        };
        return ArtemisHttpUtil.doPostStringArtemis(config, path, body, null, null, "application/json");
    }

    /**
     * 调用POST请求类型接口(有请求头)
     */
    public static String callPostApiWithHeader(String url, String body, Map<String, String> header) throws Exception {
        new BaseBean().writeLog("begin do do post string artemis...");
        ArtemisConfig config = new ArtemisConfig();
        config.setHost(HOST);
        config.setAppKey(APP_KEY);
        config.setAppSecret(APP_SECRET);
        final String getCamsApi = ARTEMIS_PATH + url;
        Map<String, String> path = new HashMap<String, String>(2) {
            {
                put("https://", getCamsApi);
            }
        };
        return ArtemisHttpUtil.doPostStringArtemis(config, path, body, null, null, "application/json", header);
    }

    public static String callPostApiList(String url, Map<String, Object> map) throws Exception {
        ArtemisConfig config = new ArtemisConfig();
        config.setHost(HOST);
        config.setAppKey(APP_KEY);
        config.setAppSecret(APP_SECRET);
        final String getCamsApi = ARTEMIS_PATH + url;
        Map<String, String> path = new HashMap<String, String>(2) {
            {
                put("https://", getCamsApi);
            }
        };
        return  ArtemisHttpUtil.doPostStringArtemis(config, path, JSON.toJSON(map).toString(),
                null, null, "application/json");
    }

    public static List<List<String>> subListByCount(List<String> data, int count) {

        List<List<String>> result = new ArrayList<>();

        int size = data.size();// 数据长度

        if (size > 0 && count > 0) {

            int segments = size / count;// 商
            /**
             * 1.整除，  即分隔为segments     段
             * 2.除不尽，即分隔为segments + 1 段
             */
            segments = size % count == 0 ? segments : segments + 1; // 段数

            List<String> cutList = null;// 每段List

            for (int i = 0; i < segments; i++) {
                if (i == segments - 1) {
                    cutList = data.subList(count * i, size);
                } else {
                    cutList = data.subList(count * i, count * (i + 1));
                }
                result.add(cutList);
            }
        } else {
            result.add(data);
        }
        return result;
    }

    public static String AfterDay(String time,long day){
        LocalDateTime localDateTime = LocalDate.parse(time, yyyyMMdd).atStartOfDay();

        return localDateTime.plusDays(day).format(yyyyMMdd);
    }

    public static String beforeDay(String time,long day){
        LocalDateTime localDateTime = LocalDate.parse(time, yyyyMMdd).atStartOfDay();
        return localDateTime.minusDays(day).format(yyyyMMdd);
    }

    public static LocalDateTime getTime(String time){
        int length = time.length();
        switch (length){
            case 10:
                return LocalDate.parse(time, yyyyMMdd).atStartOfDay();
            case 19:
                return LocalDateTime.parse(time, yyyyMMddHHmmss);
            case 16:
                return LocalDateTime.parse(time, yyyyMMddHHmm);
        }
        return null;
    }

    public static Map<String, String> getHikHrmInfo() {
        new BaseBean().writeLog("begin do getHikHrmInfo ...");
        Map<String, String> hikHrmInfoMap = new HashMap<>();
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("pageSize", "1000");
        int pageNo = 1;
        boolean isGoing = true;
        while (isGoing) {
            try {
                map.put("pageNo", String.valueOf(pageNo));
                String result = HikVisionApiUtil.callPostApi("/api/resource/v1/person/personList", JSON.toJSON(map).toString());
                JSONObject dataObj = JSON.parseObject(result).getJSONObject("data");
                JSONArray jsonList = dataObj.getJSONArray("list");
                if ((float)dataObj.getInteger("total")/1000 > pageNo) {
                    pageNo += 1;
                } else {
                    isGoing = false;
                }
                for (int i = 0; i < jsonList.size(); i++) {
                    JSONObject jsonObject = jsonList.getJSONObject(i);
                    String certificateType = jsonObject.getString("certificateType");
                    if (StringUtil.isNotEmpty(certificateType) && certificateType.equals("131")) {
                        hikHrmInfoMap.put(jsonObject.getString("certificateNo"), jsonObject.getString("personId"));
                    }
                }
            } catch (Exception e) {
                isGoing = false;
                new BaseBean().writeLog(e);
            }

        }
        new BaseBean().writeLog("end do getHikHrmInfo ...");
        return hikHrmInfoMap;
    }

    public static String imageBase64(String imgPath) {
        byte[] data = null;
        // 读取图片字节数组
        try {
            InputStream in = new FileInputStream(imgPath);
            data = new byte[in.available()];
            in.read(data);
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 对字节数组Base64编码
        BASE64Encoder encoder = new BASE64Encoder();
        // 返回Base64编码过的字节数组字符串
        String ss= encoder.encode(Objects.requireNonNull(data));
        return ss;
    }

    public  static String unzip(String filePath, String zipDir) {
        String name = "";
        String re = "";
        try {
            BufferedOutputStream dest = null;
            BufferedInputStream is = null;
            ZipEntry entry;
            ZipFile zipfile = new ZipFile(filePath);

            Enumeration dir = zipfile.entries();
            while (dir.hasMoreElements()){
                entry = (ZipEntry) dir.nextElement();

                if( entry.isDirectory()){
                    name = entry.getName();
                    name = name.substring(0, name.length() - 1);
                    File fileObject = new File(zipDir + name);
                    fileObject.mkdir();
                }
            }

            Enumeration e = zipfile.entries();
            while (e.hasMoreElements()) {
                entry = (ZipEntry) e.nextElement();
                if( entry.isDirectory()){
                    continue;
                }else{
                    is = new BufferedInputStream(zipfile.getInputStream(entry));
                    int count;
                    byte[] dataByte = new byte[BUFFER];
                    FileOutputStream fos = new FileOutputStream(zipDir+entry.getName());
                    re = zipDir+entry.getName();
                    dest = new BufferedOutputStream(fos, BUFFER);
                    while ((count = is.read(dataByte, 0, BUFFER)) != -1) {
                        dest.write(dataByte, 0, count);
                    }
                    dest.flush();
                    dest.close();
                    is.close();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return  re;
    }

    // 删除文件夹
    // param folderPath 文件夹完整绝对路径
    public static void delFolder(String folderPath) {
        try {
            // 删除完里面所有内容
            delAllFile(folderPath);
            String filePath = folderPath;
            filePath = filePath.toString();
            File myFilePath = new File(filePath);
            //删除空文件夹
            myFilePath.delete();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 删除指定文件夹下所有文件
    // param path 文件夹完整绝对路径
    public static boolean delAllFile(String path) {
        boolean flag = false;
        File file = new File(path);
        if (!file.exists()) {
            return flag;
        }
        if (!file.isDirectory()) {
            return flag;
        }
        String[] tempList = file.list();
        File temp = null;
        for (int i = 0; i < tempList.length; i++) {
            if (path.endsWith(File.separator)) {
                temp = new File(path + tempList[i]);
            } else {
                temp = new File(path + File.separator + tempList[i]);
            }
            if (temp.isFile()) {
                temp.delete();
            }
            if (temp.isDirectory()) {
                delAllFile(path + "/" + tempList[i]);// 先删除文件夹里面的文件
                delFolder(path + "/" + tempList[i]);// 再删除空文件夹
                flag = true;
            }
        }
        return flag;
    }

    public static void main(String[] args) throws Exception{
        String startDateString = "2022-01-01";
        String endDateString = "2022-01-01";
        String dateStartStr = "2022-01-01 09:00:00";
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date dateStart = simpleDateFormat.parse(dateStartStr);
        System.out.println(dateStart.getTime());
        System.out.println(dateStart.getTime() / 1000);
    }
}

